import { Module } from '@nestjs/common';
import { UserModule } from './api/user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from 'nestjs-config';
import { resolve } from 'path';
import { AuthModule } from './api/auth/auth.module';
import { ToolsService } from './api/shared/services/tools/tools.service';
import { SharedModule } from './api/shared/shared.module';
import { ArticleModule } from './api/article/article.module';
import { CommentModule } from './api/comment/comment.module';
import { TagModule } from './api/tag/tag.module';
import { RoleModule } from './api/role/role.module';
import { ResourceModule } from './api/resource/resource.module';

import { ValidationPipe } from './pipe/validation.pipe';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
@Module({
  imports: [
    // 配置加载配置文件
    ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {
      modifyConfigName: (name: string) => name.replace('.config', ''),
    }),
    // mysql的连接
    TypeOrmModule.forRootAsync({
      useFactory: async (config: ConfigService) => {
        return {
          type: config.get('database.type'),
          host: config.get('database.host'),
          port: config.get('database.port'),
          username: config.get('database.username'),
          password: config.get('database.password'),
          database: config.get('database.database'),
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          logging: config.get('database.logging'),
          synchronize: true, // 同步数据库
          timezone: '+08:00', // 东八区
          cache: {
            duration: 60000, // 1分钟的缓存
          },
          extra: {
            poolMax: 32,
            poolMin: 16,
            queueTimeout: 60000,
            pollPingInterval: 60, // 每隔60秒连接
            pollTimeout: 60, // 连接有效60秒
          },
        };
      },
      inject: [ConfigService],
    }),
    UserModule,
    AuthModule,
    SharedModule,
    ArticleModule,
    CommentModule,
    TagModule,
    RoleModule,
    ResourceModule,
  ],
  providers: [
    ToolsService,
    {
      provide: APP_INTERCEPTOR,
      useClass: TransformInterceptor,
    },
    // 全局使用管道(数据校验)
    {
      provide: APP_PIPE,
      useClass: ValidationPipe,
    },
  ],
})
export class AppModule {}
